import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class PuzzleLoader {
    private final List<List<List<Integer>>> parsedPuzzles = new LinkedList<List<List<Integer>>>();

    BufferedReader in;

    public PuzzleLoader(String filename) throws FileNotFoundException {
        FileReader fstream = new FileReader(filename);
        in = new BufferedReader(fstream);
    }

    public void parse() throws IOException {
        String line;
        int pNum = 0;
        // create first puzzle
        parsedPuzzles.add(new LinkedList<List<Integer>>());
        while ((line = in.readLine()) != null) {

            if (line.isEmpty()) {
                // skip puzzle delimiter \n
                pNum++;
                // create new puzzle
                parsedPuzzles.add(new LinkedList<List<Integer>>());
                continue;
            }
            LinkedList<Integer> row = new LinkedList<Integer>();
            for (int i = 0; i < line.length(); i++) {
                char c = line.charAt(i);
                Integer num = new Integer(0);
                // . is empty cell num rep => 0
                if (c != '.') {
                    num = Character.getNumericValue(c);
                }
                // add col nr
                row.add(num);

            }
            // add row to puzzle.
            parsedPuzzles.get(pNum).add(row);
        }
        // remove empty last
        if (parsedPuzzles.get(pNum).isEmpty()) {
            parsedPuzzles.remove(pNum);
        }
    }

    public List<List<List<Integer>>> getParsedPuzzles() {
        return parsedPuzzles;
    }

    public static List<List<Integer>> getDeepPuzzleClone(
            List<List<Integer>> puzzle) {
        List<List<Integer>> clone = new LinkedList<List<Integer>>();
        LinkedList<Integer> cloneRow;
        for (List<Integer> row : puzzle) {
            cloneRow = new LinkedList<Integer>();
            clone.add(cloneRow);
            for (Integer col : row) {
                cloneRow.add(new Integer(col.intValue()));
            }
        }
        return clone;
    }
}
